/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pracamagisterska;

import java.awt.Color;
import java.awt.Toolkit;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JOptionPane;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

/**
 *
 * @author Adrian
 */
public class Card extends ModalityInternalFrame {
    private org.jbundle.thin.base.screen.jcalendarbutton.JCalendarButton jCalendarButton1;
    private org.jbundle.thin.base.screen.jcalendarbutton.JCalendarButton jCalendarButton2;
    DatabaseThread db;
    int index;
    /**
     * Creates new form Card
     */
    public Card(JComponent parent,ReviewList item,DatabaseThread db,int index) throws ParseException {
        super(parent,item,db,index);
        initComponents();
        initCalendars();
        this.db=db;
        this.index=index;
        if(item!=null){
            jTextField1.setText(item.getCheckin());
            jTextField2.setText(item.getCheckout());
            jTextField3.setText(item.getApt()+"");
            jTextField4.setText(((Review) parent).getCardNumber());
            countDates();
        }
        ((AbstractDocument)jTextField3.getDocument()).setDocumentFilter(
                new MyDocumentFilter()); 

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField5 = new javax.swing.JTextField();
        jTextField6 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();

        jLabel1.setText("Check-in:");

        jLabel2.setText("Check-out:");

        jLabel3.setText("Numer pokoju:");

        jLabel4.setText("Nr karty:");

        jTextField1.setEditable(false);

        jTextField2.setEditable(false);

        jTextField4.setEditable(false);
        jTextField4.setDisabledTextColor(new java.awt.Color(0, 0, 0));
        jTextField4.setEnabled(false);

        jButton1.setText("Zapisz");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Anuluj");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTextField5.setEditable(false);
        jTextField5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jTextField5.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextField5.setDisabledTextColor(new java.awt.Color(255, 0, 0));
        jTextField5.setEnabled(false);

        jTextField6.setEditable(false);
        jTextField6.setDisabledTextColor(new java.awt.Color(0, 0, 0));
        jTextField6.setEnabled(false);

        jLabel5.setText("Ilość dni:");

        jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/childish_file.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(88, 88, 88)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(34, 34, 34)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextField1)
                            .addComponent(jTextField2)
                            .addComponent(jTextField3)
                            .addComponent(jTextField4)
                            .addComponent(jTextField6, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 15, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(31, 31, 31))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(127, 127, 127))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33)
                .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(30, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void initCalendars(){
        jCalendarButton1 = new org.sourceforge.jcalendarbutton.JCalendarButton(); 
        jCalendarButton1.addPropertyChangeListener(new java.beans.PropertyChangeListener(){  
            @Override
            public void propertyChange(java.beans.PropertyChangeEvent evt) { 
            if (evt.getNewValue() instanceof Date) setDate((Date)evt.getNewValue()); 
        }
            private void setDate(Date date) {
                try {
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");                
                    jTextField1.setText(dateFormat.format(date));
                    countDates();
                } catch (ParseException ex) {
                    Logger.getLogger(Card.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        this.add(jCalendarButton1);
        jCalendarButton1.setLocation(300,213);
        jCalendarButton1.setSize(34,34);    
        //--- drugi przycisk
        jCalendarButton2 = new org.sourceforge.jcalendarbutton.JCalendarButton(); 
        jCalendarButton2.addPropertyChangeListener(new java.beans.PropertyChangeListener(){  
            @Override
            public void propertyChange(java.beans.PropertyChangeEvent evt) { 
            if (evt.getNewValue() instanceof Date) setDate((Date)evt.getNewValue()); 
        }
            private void setDate(Date date){
                try {
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");                
                    jTextField2.setText(dateFormat.format(date));
                    countDates();
                } catch (ParseException ex) {
                    Logger.getLogger(Card.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        this.add(jCalendarButton2);
        jCalendarButton2.setLocation(300,248);
        jCalendarButton2.setSize(34,34);    
    }
    private void countDates() throws ParseException{
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(jTextField1.getText().length()>1 && jTextField2.getText().length()>1) {
            Date date1 = sdf.parse(jTextField1.getText());
            Date date2 = sdf.parse(jTextField2.getText());
            jTextField6.setText((int)((date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24))+"");
        }
    }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            if(validateData()){
                ModalityInternalFrame wrg = new Warning(this,"Czy jesteś pewien ?",db);
                JDesktopPane desktop = JOptionPane.getDesktopPaneForComponent(this);           
                desktop.add(wrg);
                wrg.show(); 
            }
        } catch (ParseException ex) {
            Logger.getLogger(Card.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        ModalityInternalFrame wrg = new Warning(this,"Czy chcesz porzucić zmiany ?");
        JDesktopPane desktop = JOptionPane.getDesktopPaneForComponent(this);           
        desktop.add(wrg);
        wrg.show(); 
    }//GEN-LAST:event_jButton2ActionPerformed

    private boolean validateData() throws ParseException{
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            jTextField1.setBackground(Color.white);
            jTextField2.setBackground(Color.white);
            jTextField3.setBackground(Color.white);
        if(jTextField1.getText().length()<1){
            jTextField5.setText("Nieprawidłowa data check-in");
            jTextField1.setBackground(Color.YELLOW);
            return false;
        }
        if(jTextField2.getText().length()<1){
            jTextField1.setBackground(Color.white);
            jTextField2.setBackground(Color.YELLOW);
            jTextField5.setText("Nieprawidłowa data check-out");
            return false;
        }
        Date date1 = sdf.parse(jTextField1.getText());
        Date date2 = sdf.parse(jTextField2.getText());
        if(date1.after(new Date())) {
            jTextField1.setBackground(Color.YELLOW);
            jTextField5.setText("Nie można zameldować się z wyprzedzeniem!");
            return false;
        }
        if(date1.equals(date2)){
            jTextField1.setBackground(Color.YELLOW);
            jTextField2.setBackground(Color.YELLOW);
            jTextField5.setText("Długość pobytu nie może wynosić 0 dni!");
            return false;
        }
        if(date2.before(date1)) {
            jTextField1.setBackground(Color.YELLOW);
            jTextField2.setBackground(Color.YELLOW);
            jTextField5.setText("Najpierw należy się zameldować! Sprawdź daty.");
            return false;
        }
        if(jTextField3.getText().length()<1 || jTextField3.getText().length()>5){            
            jTextField1.setBackground(Color.white);
            jTextField2.setBackground(Color.white);
            jTextField3.setBackground(Color.yellow);
            jTextField5.setText("Nieprawidłowy numer apartamentu (max. 5 cyfr)");
            return false;
        }
        return true;
    }
    protected void childparentClosing(boolean status) throws SQLException{
        if(!status){ //anuluj zmiany
            getGlassPane().setVisible(false);
            setChildFrame(null);        
            this.dispose();
            ((Review) parent).childClosing();
        }else{ //dodaj / update karty
            if(jTextField4.getText().equals("")){ //dodaj                  
                    db.Card_change(new ReviewList(jTextField1.getText(),jTextField2.getText(),Integer.parseInt(jTextField3.getText())),0);
                    ((Review) parent).newCard(jTextField1.getText());
                    getGlassPane().setVisible(false);
                    setChildFrame(null);        
                    this.dispose();
                    ((Review) parent).childClosing();
            }else{//update
                db.Card_change(new ReviewList(jTextField1.getText(),jTextField2.getText(),Integer.parseInt(jTextField3.getText())),index);
                ((Review) parent).refresh();
                getGlassPane().setVisible(false);
                setChildFrame(null);        
                this.dispose();
                ((Review) parent).childClosing();
            }
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    // End of variables declaration//GEN-END:variables
}

class MyDocumentFilter extends DocumentFilter
{   
    @Override
    public void insertString(DocumentFilter.FilterBypass fp
            , int offset, String string, AttributeSet aset)
                                throws BadLocationException
    {
        int len = string.length();
        boolean isValidInteger = true;

        for (int i = 0; i < len; i++)
        {
            if (!Character.isDigit(string.charAt(i)))
            {
                isValidInteger = false;
                break;
            }
        }
        if (isValidInteger)
            super.insertString(fp, offset, string, aset);
        else
            Toolkit.getDefaultToolkit().beep();
    }

    @Override
    public void replace(DocumentFilter.FilterBypass fp, int offset
                    , int length, String string, AttributeSet aset)
                                        throws BadLocationException
    {
        int len = string.length();
        boolean isValidInteger = true;

        for (int i = 0; i < len; i++)
        {
            if (!Character.isDigit(string.charAt(i)))
            {
                isValidInteger = false;
                break;
            }
        }
        if (isValidInteger)
            super.replace(fp, offset, length, string, aset);
        else
            Toolkit.getDefaultToolkit().beep();
    }
}